package com.weilus.config.security;

import com.alibaba.druid.util.StringUtils;
import com.weilus.service.cache.ImageCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ValidImageCodeFilter extends OncePerRequestFilter {
    public static final Logger logger = LoggerFactory.getLogger(ValidImageCodeFilter.class);

    @Autowired
    ImageCodeService imageCodeService;

    RequestMatcher requiresValidImageCodetMatcher;

    public ValidImageCodeFilter(){
        requiresValidImageCodetMatcher = new AntPathRequestMatcher("/login", "POST");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if(requiresValidImageCodetMatcher.matches(httpServletRequest)) {
            logger.info("登入校验验证码.....");
            String key = httpServletRequest.getParameter("key"), code = httpServletRequest.getParameter("code");
            if (StringUtils.isEmpty(key) || StringUtils.isEmpty(code) || !code.equalsIgnoreCase(imageCodeService.getLoginImageCode(key))) {
                httpServletResponse.sendRedirect("/login.html?err=2");
                return;
            }
            logger.info("验证码正确。。。");
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
